package com.shanzmoo.core.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.core.cache.CurrentUserCache;
import com.shanzmoo.db.picture.entity.ProductInfoPictureEntity;
import com.shanzmoo.db.picture.entity.ProductPictureEntity;
import com.shanzmoo.db.picture.service.IProductInfoPictureService;
import com.shanzmoo.db.picture.service.IProductPictureService;
import com.shanzmoo.db.product.entity.ProductBrandEntity;
import com.shanzmoo.db.product.entity.ProductSkuEntity;
import com.shanzmoo.db.product.entity.ProductSpuEntity;
import com.shanzmoo.db.product.entity.ProductUnitEntity;
import com.shanzmoo.db.product.entity.dto.CatsDto;
import com.shanzmoo.db.product.entity.dto.ProductSaveDto;
import com.shanzmoo.db.product.entity.dto.ProductSpuActualSaleDTO;
import com.shanzmoo.db.product.entity.dto.ProductSpuDto;
import com.shanzmoo.db.product.entity.vo.BrandQueryVO;
import com.shanzmoo.db.product.entity.vo.ProductQueryVO;
import com.shanzmoo.db.product.entity.vo.ProductVO;
import com.shanzmoo.db.product.entity.vo.UnitQueryVO;
import com.shanzmoo.db.product.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 *
 * @author： Gzhao 2021/1/31
 */
@Slf4j
@Component
public class ProductManager {

    @Autowired
    private IProductSpuService productSpuService;
    @Autowired
    private IProductSkuService productSkuService;
    @Autowired
    private IProductPictureService productPictureService;
    @Autowired
    private IProductInfoPictureService productInfoPictureService;
    @Autowired
    private IProductCategoryService productCategoryService;
    @Autowired
    private IProductBrandService productBrandService;
    @Autowired
    private IProductUnitService productUnitService;
    @Autowired
    CodeManager codeManager;


    /**
     * spu列表信息
     * @param productQueryVO
     * @return
     */
    public SResponse<PageRespBase<ProductVO>> getSpuList(ProductQueryVO productQueryVO) {
        // 开启分页
        Page page = PageHelper.startPage(productQueryVO.getPageNum(), productQueryVO.getPageSize());
        List<ProductVO> productVOList = productSpuService.getSpuList(productQueryVO);
        for (ProductVO productVO : productVOList) {
            if(StrUtil.isNotBlank(productVO.getCategoryName1())){
                String categoryNames = productVO.getCategoryName1();
                String[] names = categoryNames.split(",");
                if(names.length != 3) {
                    SResponse.fail(Constant.ERRCODE_PRODUCT_CATEGORYIDLENGTH, "错误商品分类级别:"+names.length);
                }
                productVO.setCategoryName1(names[0]);
                productVO.setCategoryName2(names[1]);
                productVO.setCategoryName3(names[2]);
            }else{
                SResponse.fail(Constant.ERRCODE_PRODUCT_CATEGORYNAME, "商品分类名未找到");
            }
        }
        PageRespBase<ProductVO> re = PageRespBase.create(page, productVOList);
        PageHelper.clearPage();
        return SResponse.ok(re);
    }

    /**
     * 保存spu和sku信息
     * @param productSaveDto
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public SResponse<Boolean> saveSpu(ProductSaveDto productSaveDto) {
        //保存spu信息
        ProductSpuEntity productSpuEntity = productSaveDto.getSpuEntity();
        productSpuEntity.setCreateUser(CurrentUserCache.getUserId());
        productSpuEntity.setSpu(codeManager.generateSpu(productSpuEntity.getCategoryId(),productSpuEntity.getBrandId()));
        productSpuService.save(productSpuEntity);

        //保存sku信息
        List<ProductSkuEntity> productSkuEntityList = productSaveDto.getSkuEntityList();
        productSkuEntityList.stream().forEach(r -> {
            r.setParentId(productSpuEntity.getId());
            r.setSku(codeManager.generateSku(productSpuEntity.getSpu()));
            r.setCreateUser(CurrentUserCache.getUserId());
        });
        productSkuService.saveBatch(productSkuEntityList);
        //处理图片信息
        handlerPicture(productSpuEntity.getId(),productSaveDto.getInfoPictureList(),productSaveDto.getProductPictureList());
        return SResponse.ok();
    }

    /**
     * 更新spu和sku信息
     * @param productSaveDto
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public SResponse<Boolean> updateSpu(ProductSaveDto productSaveDto) {
        Integer currentUserId = CurrentUserCache.getUserId();
        //保存spu信息
        ProductSpuEntity productSpuEntity = productSaveDto.getSpuEntity();
        productSpuEntity.setUpdateUser(currentUserId);
        productSpuService.updateById(productSpuEntity);

        //保存sku信息
        List<ProductSkuEntity> productSkuEntityList = productSaveDto.getSkuEntityList();
        for (ProductSkuEntity productSkuEntity : productSkuEntityList) {
            if(productSkuEntity.getId() != null){
                //更新
                productSkuEntity.setUpdateUser(currentUserId);
                productSkuService.updateById(productSkuEntity);
            }else{
                //插入
                productSkuEntity.setParentId(productSpuEntity.getId());
                productSkuEntity.setSku(codeManager.generateSku(productSpuEntity.getSpu()));
                productSkuEntity.setCreateUser(currentUserId);
                productSkuService.save(productSkuEntity);
            }
        }
        //删除前端返回不存在,后端存在的sku
        List<Integer> productNoList = productSkuEntityList.stream().map(ProductSkuEntity::getId).collect(Collectors.toList());
        productSpuService.flagWaitDeleteSku(productSpuEntity.getId(),productNoList);
        //处理图片信息
        handlerPicture(productSpuEntity.getId(),productSaveDto.getInfoPictureList(),productSaveDto.getProductPictureList());
        return SResponse.ok();
    }

    public SResponse<ProductSaveDto> getSpuDetailBySpuId(Integer spuId) {
        ProductSaveDto productSaveDto = new ProductSaveDto();
        ProductSpuEntity spuEntity = productSpuService.getById(spuId);
        productSaveDto.setSpuEntity(spuEntity);
        List<ProductSkuEntity> skuList = productSkuService.getSkuListBySpuId(spuId);
        productSaveDto.setSkuEntityList(skuList);
        //获取图片信息
        List<ProductPictureEntity> productPictureList =  productPictureService.getPicturesBySpuId(spuId);
        productSaveDto.setProductPictureList(productPictureList);
        List<ProductInfoPictureEntity> infoPictureList =  productInfoPictureService.getInfoBySpuId(spuId);
        productSaveDto.setInfoPictureList(infoPictureList);
        return SResponse.ok(productSaveDto);
    }

    public Integer getSpuIndex(Integer categoryId, Integer brandId) {
        return productSpuService.getSpuIndex(categoryId, brandId);
    }

    /**
     *
     * @param spuId
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public SResponse<Boolean> createdBySpu(Integer spuId,Integer num) {
        SResponse<ProductSaveDto> spuDetailBySpuId = getSpuDetailBySpuId(spuId);
        ProductSaveDto productSaveDto = spuDetailBySpuId.getData();
        if(productSaveDto == null){
            SResponse.fail(Constant.ERRCODE_PRODUCT_ID, "没有找到spu");
        }
        //获取品牌列表
        List<ProductBrandEntity> brandList = productBrandService.getBrandListMethod(new BrandQueryVO());
        int brandSize = brandList.size();
        //获取单位列表
        List<ProductUnitEntity> unitList = productUnitService.getUnitListMethod(new UnitQueryVO());
        int unitSize = unitList.size();
        //获取分类列表
        List<CatsDto> catsDtoList =  productCategoryService.getCatIdAndParents();
        int catSize = catsDtoList.size();
        for(int i = 1;i < num+1;i++){
            ProductSpuEntity spuEntity = productSaveDto.getSpuEntity();
            spuEntity.setId(null);
            spuEntity.setName("第"+i+"个自动生成商品");
            spuEntity.setSubheading("副标题 " + RandomUtil.randomString(5));
            spuEntity.setSpu(codeManager.generateSpu(spuEntity.getCategoryId(),spuEntity.getBrandId()));
            spuEntity.setUnitId(unitList.get(RandomUtil.randomInt(0,unitSize-1)).getId());
            spuEntity.setBrandId(brandList.get(RandomUtil.randomInt(0,brandSize-1)).getId());
            CatsDto catsDto = catsDtoList.get(RandomUtil.randomInt(0, catSize-1));
            spuEntity.setCategoryId(catsDto.getCat3Id());
            spuEntity.setCategoryIds(catsDto.getCat1Id()+","+catsDto.getCat2Id()+","+catsDto.getCat3Id());
            productSpuService.save(spuEntity);

            List<ProductSkuEntity> productSkuEntityList = productSaveDto.getSkuEntityList();
            productSkuEntityList.stream().forEach(r -> {
                r.setId(null);
                r.setParentId(spuEntity.getId());
                r.setSku(codeManager.generateSku(spuEntity.getSpu()));
                r.setCreateUser(CurrentUserCache.getUserId());
            });
            productSkuService.saveBatch(productSkuEntityList);
        }
        return SResponse.ok();
    }

    public List<ProductSpuDto> getAllSpuDto() {
        return productSpuService.getAllSpuDto();
    }

    public List<ProductSpuActualSaleDTO> getSpuActualSales(List<String> spuIds) {
        return productSpuService.getSpuActualSales(spuIds);
    }

    /**
     * 处理图片信息
     */
    private void handlerPicture(Integer id,List<ProductInfoPictureEntity> infoPictureList,List<ProductPictureEntity> productPictureList){
        //先删除spu关联的详情图和商品图
        productInfoPictureService.update(new UpdateWrapper<ProductInfoPictureEntity>().eq("product_id",id).set("deleted",true));
        productPictureService.update(new UpdateWrapper<ProductPictureEntity>().eq("product_id",id).set("deleted",true));
        //新增商品详情
        if(CollUtil.isNotEmpty(infoPictureList)){
            infoPictureList.stream().forEach(r -> {
                r.setCreateUser(CurrentUserCache.getUserId());
                r.setProductId(id);
            });
            productInfoPictureService.saveBatch(infoPictureList);
        }
        if(CollUtil.isNotEmpty(productPictureList)){
            //新增商品图片
            productPictureList.stream().forEach(r -> {
                r.setCreateUser(CurrentUserCache.getUserId());
                r.setProductId(id);
            });
            productPictureService.saveBatch(productPictureList);
        }



    }
}
